﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using System;

namespace iTool.Validator
{
    /// <summary>
    /// 控制器数据验证
    /// </summary>
    public abstract class ControllerValidatorAttribute : Attribute, IActionFilter
    {
        /// <summary>
        /// Action 执行后
        /// </summary>
        /// <param name="context"></param>
        public virtual void OnActionExecuted(ActionExecutedContext context)
        {
            
        }

        /// <summary>
        /// Action 执行前
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="context"></param>
        public virtual void OnActionExecuting(ActionExecutingContext context)
        {
            // 获取验证方法
            var method = ValidatorMethodsInfoCache.GetMethod( context.ActionDescriptor,this.GetType());

            if (method != null)
            {
                // 获取验证参数
                var invokeParameters = ValidatorUtils.GetMethodParameterByActionArguments(context.ActionArguments);

                try
                {
                    // 执行验证
                    method.Invoke(this, invokeParameters);
                }
                catch (Exception e)
                {
                    // 验证未通过
                    var result = this.ValidatorError(e.InnerException.Message);

                    context.Result = new ObjectResult(result);
                }
                
            }

        }

        /// <summary>
        /// 错误信息
        /// </summary>
        /// <param name="error"></param>
        /// <returns></returns>
        public virtual object ValidatorError(string error)
        {
            return new {
                code = 10003,
                info = error,
                data = string.Empty
            };
        }


    }
}
